import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function POST(request: NextRequest) {
  try {
    console.log("开始修复缺失的参数数据...");
    
    const database = new SqliteDatabase();
    
    // 获取所有设备
    const allDevices = database.getAllDevices();
    console.log(`找到 ${allDevices.length} 个设备`);
    
    // 定义参数字段
    const namingFields = [
      { name: "设计物资编码", dataType: "字符型", required: false },
      { name: "采购物资编码", dataType: "字符型", required: false },
      { name: "采购包号批次", dataType: "字符型", required: false },
      { name: "制造出厂编码", dataType: "字符型", required: false },
      { name: "物流编码", dataType: "字符型", required: false },
      { name: "仓储编码", dataType: "字符型", required: false },
      { name: "施工物资编码", dataType: "字符型", required: false },
      { name: "施工自编号", dataType: "字符型", required: false },
      { name: "运行资产编码", dataType: "字符型", required: false },
      { name: "石油天然气行业设备编码", dataType: "字符型", required: false },
      { name: "运行自编号", dataType: "字符型", required: false },
      { name: "流水码", dataType: "字符型", required: false }
    ];
    
    const positionFieldsC4 = [
      { name: "设计设备位号 / 管线号", dataType: "字符型", required: true },
      { name: "工厂地址", dataType: "字符型", required: false },
      { name: "工厂坐标", dataType: "字符型", required: false },
      { name: "物流地理信息", dataType: "字符型", required: false },
      { name: "物流坐标", dataType: "字符型", required: false },
      { name: "仓储地址", dataType: "字符型", required: false },
      { name: "仓储坐标", dataType: "字符型", required: false },
      { name: "施工设备位号", dataType: "字符型", required: false },
      { name: "施工 / 运行坐标", dataType: "字符型", required: false },
      { name: "运行设备位号", dataType: "字符型", required: false }
    ];
    
    const positionFieldsC6 = [
      { name: "设计设备位号/管线号", dataType: "字符型", required: true },
      { name: "工厂地址", dataType: "字符型", required: false },
      { name: "工厂坐标", dataType: "字符型", required: false },
      { name: "物流地理信息", dataType: "字符型", required: false },
      { name: "物流坐标", dataType: "字符型", required: false },
      { name: "仓储地址", dataType: "字符型", required: false },
      { name: "仓储坐标", dataType: "字符型", required: false },
      { name: "施工设备位号", dataType: "字符型", required: false },
      { name: "施工管线号", dataType: "字符型", required: false },
      { name: "施工/运行坐标", dataType: "字符型", required: false },
      { name: "运行设备位号", dataType: "字符型", required: false },
      { name: "运行管线号", dataType: "字符型", required: false }
    ];
    
    const defaultBaseFields = [
      { name: "规格", dataType: "字符型", unit: "", required: true },
      { name: "型号", dataType: "字符型", unit: "", required: true },
      { name: "制造厂家", dataType: "字符型", unit: "", required: true },
      { name: "供货厂家", dataType: "字符型", unit: "", required: true },
      { name: "设备名称", dataType: "字符型", unit: "", required: true }
    ];
    
    let fixedDevices = 0;
    let addedParameters = 0;
    
    // 检查每个设备的参数完整性并修复
    for (const device of allDevices) {
      const deviceId = device.id!;
      let deviceFixed = false;
      
      // 检查并修复命名参数
      const existingNamingParams = database.getNamingParametersByDeviceId(deviceId);
      if (existingNamingParams.length === 0) {
        console.log(`为设备 ${device.name} (ID: ${deviceId}) 添加命名参数...`);
        for (const field of namingFields) {
          database.insertNamingParameter({
            device_id: deviceId,
            parameter_name: field.name,
            parameter_value: "",
            data_type: field.dataType,
            is_required: field.required
          });
          addedParameters++;
        }
        deviceFixed = true;
      }
      
      // 检查并修复位置参数
      const existingPositionParams = database.getPositionParametersByDeviceId(deviceId);
      if (existingPositionParams.length === 0) {
        console.log(`为设备 ${device.name} (ID: ${deviceId}) 添加位置参数...`);
        const positionFields = device.position_table_id === "表 C.6" ? positionFieldsC6 : positionFieldsC4;
        for (const field of positionFields) {
          database.insertPositionParameter({
            device_id: deviceId,
            parameter_name: field.name,
            parameter_value: "",
            data_type: field.dataType,
            is_required: field.required
          });
          addedParameters++;
        }
        deviceFixed = true;
      }
      
      // 检查并修复基础参数
      const existingBaseParams = database.getBaseParametersByDeviceId(deviceId);
      if (existingBaseParams.length === 0) {
        console.log(`为设备 ${device.name} (ID: ${deviceId}) 添加基础参数...`);
        for (const field of defaultBaseFields) {
          database.insertBaseParameter({
            device_id: deviceId,
            parameter_name: field.name,
            data_type: field.dataType,
            measurement_class: field.unit,
            example_description: ""
          });
          addedParameters++;
        }
        deviceFixed = true;
      }
      
      if (deviceFixed) {
        fixedDevices++;
      }
    }
    
    console.log(`修复完成！为 ${fixedDevices} 个设备添加了 ${addedParameters} 个参数`);
    
    return NextResponse.json({
      success: true,
      message: `成功修复缺失的参数数据，为 ${fixedDevices} 个设备添加了 ${addedParameters} 个参数`,
      data: {
        totalDevices: allDevices.length,
        fixedDevices: fixedDevices,
        addedParameters: addedParameters,
        parameterTypes: {
          naming: namingFields.length,
          position: "根据设备位置表类型（C.4或C.6）",
          base: defaultBaseFields.length
        }
      }
    });
    
  } catch (error) {
    console.error("修复缺失参数时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "修复缺失参数过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 